import { defineStore } from 'pinia'
import { authService } from '../services/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false
  }),

  getters: {
    isAdmin: (state) => state.user?.role === 'admin',
    currentUser: (state) => state.user,
    hasPermission: (state) => (permission) => {
      if (!state.user) return false
      if (state.user.role === 'admin') return true
      return state.user.permissions?.includes(permission) || false
    }
  },

  actions: {
    async login(credentials) {
      try {
        const response = await authService.login(credentials)
        this.user = response.user
        this.token = response.token
        this.isAuthenticated = true
        return { success: true, user: response.user }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    async register(userData) {
      try {
        const response = await authService.register(userData)
        this.user = response.user
        this.token = response.token
        this.isAuthenticated = true
        return { success: true, user: response.user }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
    },

    async updateProfile(userData) {
      try {
        const response = await authService.updateProfile(this.token, userData)
        this.user = { ...this.user, ...response.user }
        return { success: true, user: response.user }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    async changePassword(passwordData) {
      try {
        await authService.changePassword(this.token, passwordData)
        return { success: true }
      } catch (error) {
        return { success: false, message: error.message }
      }
    },

    restoreAuth() {
      const savedToken = localStorage.getItem('auth_token')
      const savedUser = localStorage.getItem('auth_user')
      
      if (savedToken && savedUser) {
        try {
          this.token = savedToken
          this.user = JSON.parse(savedUser)
          this.isAuthenticated = true
        } catch (error) {
          this.clearStoredAuth()
        }
      }
    },

    storeAuth() {
      if (this.token && this.user) {
        localStorage.setItem('auth_token', this.token)
        localStorage.setItem('auth_user', JSON.stringify(this.user))
      }
    },

    clearStoredAuth() {
      localStorage.removeItem('auth_token')
      localStorage.removeItem('auth_user')
    }
  },

  persist: {
    enabled: true,
    strategies: [
      {
        key: 'auth',
        storage: localStorage,
        paths: ['user', 'token', 'isAuthenticated']
      }
    ]
  }
})